﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace perfume.Models.DB
{
    public partial class ShoppingCart
    {

        perfume_dbEntities per_db = new perfume_dbEntities();
        string ShoppingCartId { get; set; }
        public const string CartSesstionKey = "CartId";
        public static ShoppingCart GetCart(HttpContextBase context)
        {
            var cart = new ShoppingCart();
            cart.ShoppingCartId = cart.GetCartId(context);
            return cart;
        }


        // Helper method to simplify shopping cart calls
        public static ShoppingCart GetCart(Controller controller)
        {
            return GetCart(controller.HttpContext);
        }

        [Authorize]
        public void AddToCart(product product)
        {
            // Get the matching cart and Product instances
            
            var cartItem = per_db.carts.SingleOrDefault(
                c => c.cart_id == ShoppingCartId
                && c.product_id == product.product_id);

            if (cartItem == null)
            {
                // Create a new cart item if no cart item exists
                cartItem = new cart
                {
                    //record_id=,///coi lai cho nay tu dong tang record
                    //record_id=10,
                    product_id = product.product_id,
                    cart_id = ShoppingCartId,
                    count = 1,
                    date_creat = DateTime.Now
                };
                per_db.AddTocarts(cartItem);
            }
            else
            {
                //Tang so luong  len 1 
                //Neu da co trong gio hang
                cartItem.count++;
            }
            // Save changes
            per_db.SaveChanges();
        }

        public void UpdateQuantity(product product, int quantity)
        {
            // Get the matching cart and Product instances
            var cartItem = per_db.carts.SingleOrDefault(
                c => c.cart_id == ShoppingCartId
                    && c.product_id == product.product_id);

            if (cartItem == null)
            {
                // Create a new cart item if no cart item exists
                cartItem = new cart
                {
                    product_id = product.product_id,
                    cart_id = ShoppingCartId,
                    count = quantity,
                    date_creat = DateTime.Now
                };
                per_db.AddTocarts(cartItem);
            }
            else
            {
                cartItem.count += quantity;
            };
            per_db.SaveChanges();
        }

        public int RemoveFromCart(int id)
        {
            // Get the cart
            var cartItem = per_db.carts.Single(
                c => c.cart_id == ShoppingCartId
                    && c.record_id == id);

            int itemCount = 0;

            if (cartItem != null)
            {
                if (cartItem.count > 1)
                {
                    cartItem.count--;
                    itemCount = cartItem.count;
                }
                else
                {
                    per_db.carts.DeleteObject(cartItem);
                }
                // Save changes
                per_db.SaveChanges();
            }
            return itemCount;
        }

        public void EmptyCart()
        {


            var cartItems = per_db.carts.Where(
                c => c.cart_id == ShoppingCartId);

            foreach (var cartItem in cartItems)
            {
                per_db.carts.DeleteObject(cartItem);
            }
            // Save changes
            per_db.SaveChanges();

        }

        public List<cart> GetCartItems()
        {
            return per_db.carts.Where(
                c => c.cart_id == ShoppingCartId).ToList();
        }

        public int GetCount()
        {
            // Get the count of each item in the cart and sum them up
            int? count = (from cartItems in per_db.carts
                          where cartItems.cart_id == ShoppingCartId
                          select (int?)cartItems.count).Sum();
            // Return 0 if all entries are null
            return count ?? 0;
        }

        public decimal GetTotal()
        {
            decimal? total = (from cartItems in per_db.carts
                              where cartItems.cart_id == ShoppingCartId
                              select (int?)cartItems.count *
                             (int?)cartItems.product.price).Sum();//khoa ngoai


            return total ?? decimal.Zero;
        }

        public int CreateExport(export_check export)
        {
            decimal orderTotal = 0;


            var cartItems = GetCartItems();
            // Iterate over the items in the cart, 
            // adding the order details for each
            foreach (var item in cartItems)
            {
                var export_detail = new export_check_detail
                {
                    product_id = item.product_id,
                    export_check_id = export.export_check_id,
                    export_check_amount = item.count
                };
                // Set the order total of the shopping cart
                //db.OrderDetails.AddObject(orderDetail);
                per_db.AddToexport_check_detail(export_detail);
                orderTotal += (item.count * Convert.ToInt32(item.product.price));

            }
            // order.Total = orderTotal;
            per_db.SaveChanges();
            EmptyCart();
            // Return the OrderId as the confirmation number
            return export.export_check_id;
        }
        // We're using HttpContextBase to allow access to cookies.

        public string GetCartId(HttpContextBase context)
        {
            if (context.Session[CartSessionKey] == null)
            {
                //if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
                //{
                //    context.Session[CartSessionKey] =
                //        context.User.Identity.Name;
                //}
                //else
                //{
                // Generate a new random GUID using System.Guid class
                Guid tempCartId = Guid.NewGuid();
                // Send tempCartId back to client as a cookie
                context.Session[CartSessionKey] = tempCartId.ToString();
                //}
            }
            return context.Session[CartSessionKey].ToString();
        }

        //Khi khách hàng login vào
        //Tự động cập nhật Mã khách Hàng vào AccountId

        public void UpdateAccountIntoCart(string username)
        {


            var shoppingCart = per_db.carts.Where(
                c => c.cart_id == ShoppingCartId);

            foreach (cart item in shoppingCart)
            {
                item.username = username;
            }
            per_db.SaveChanges();
        }

        public static string CartSessionKey { get; set; }

    }
}